import { type BaseRequest } from '@/types/request'
import { useUserStore } from '@/store/user'
import { ApiStatus } from './status'
import { type BaseResult } from '@/types/request'

const baseUrl = 'http://172.18.0.115:6060/api'

const { getIsLogin, getToken } = useUserStore()
const isLogin = getIsLogin()

export function buildQuery(params: Record<string, any>, prefix = ''): string {
  const queryParts: string[] = []

  for (const key in params) {
    if (!params.hasOwnProperty(key)) continue
    const value = params[key]
    if (value === null || typeof value === 'undefined') continue

    const prefixedKey = prefix ? (Array.isArray(params) ? `${prefix}[]` : `${prefix}[${key}]`) : key

    if (typeof value === 'object' && !(value instanceof File)) {
      queryParts.push(buildQuery(value, prefixedKey))
    } else {
      queryParts.push(`${encodeURIComponent(prefixedKey)}=${encodeURIComponent(value)}`)
    }
  }

  return queryParts.join('&')
}

async function request<T = any>(config: BaseRequest): Promise<T> {
  try {
    const res = await uni.request({
      url: baseUrl + config.url + `?${buildQuery(config.params)}`,
      method: config.method,
      data: config.data ?? {},
      header: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    })
    return res.data as T
  } catch (e) {
    uni.showToast({ title: JSON.stringify(e), icon: 'none' })
    return Promise.reject(e)
  }
}

uni.addInterceptor('request', {
  invoke: (args) => {
    // 请求拦截操作
    if (isLogin) {
      args.header.token = getToken()
    }
    return args
  },
  success: (args) => {
    let data: BaseResult
    // 响应拦截操作
    data = args.data
    if (data.code !== ApiStatus.SUCCESS) {
      uni.showToast({ title: data.info, icon: 'none' })
    }
    return args
  }
})

const api = {
  get<T>(config: BaseRequest): Promise<T> {
    return request({ ...config, method: 'GET' })
  },
  post<T>(config: BaseRequest): Promise<T> {
    return request({ ...config, method: 'POST' })
  },
  put<T>(config: BaseRequest): Promise<T> {
    return request({ ...config, method: 'PUT' })
  },
  del<T>(config: BaseRequest): Promise<T> {
    return request({ ...config, method: 'DELETE' })
  },
  request<T>(config: BaseRequest): Promise<T> {
    return request({ ...config })
  }
}

export default api
